Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C.
Lets start with a simple code.
In [ ]:
x = 34 - 23 # A comment.
y = "Hello" # Another one.
z = 3.45
if z == 3.45 or y == "Hello":
x = x + 1
y = y + " World" # String concat.
print (x)
print (y)
• Assignment uses = and comparison uses ==.
• For numbers + - * / % are as expected.
• Special use of + for string concatenation.
• Special use of % for string formatting (as with printf in C)
• Logical operators are words (and, or, not) not symbols
• The basic printing command is print.
• The first assignment to a variable creates it.
• Variable types don’t need to be declared.
• Python figures out the variable types on its own.
If you didn't get it, don't worry.
You can use Python as calculator also.
In [ ]:
2 * 3
• Strings
Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes or double quotes.
foo = "spam eggs"
Use triple double-quotes for multi-line strings or strings than contain both ‘ and “ inside of them.
foo_string = """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
In [ ]:
x = 3
y = 4.56
foo = "spam eggs"
foo_string = """
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
"""
print (x)
print (foo_string)
Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0. There is no separate character type; a character is simply a string of size one. Example
In [ ]:
bar = "hello world welcome to python workshop"
print (bar)
# Prints first 4 characters
print (bar[0:4])
# Prints Everything except first 4 characters
print (bar[4:])
# Prints the last character
print (bar[-1])
# Prints Everything except the last two characters
print (bar[:-2])
Strings can be concatenated (glued together) with the + operator, and repeated with *.
In [ ]:
string_1 = "hello "
string_2 = "world"
print (string_1 + string_2)
print (5 * string_2)
Whitespace is meaningful in Python: especially indentation and placement of newlines.
• Use a newline to end a line of code.
• Use \ when must go to next line prematurely.
• No braces { } to mark blocks of code in Python. Use consistent indentation instead.
• The first line with less indentation is outside of the block.
• The first line with more indentation starts a nested block.
• Often a colon appears at the start of a new block.
(E.g. for function and class definitions.)
• Binding a variable in Python means setting a name to hold a reference to some object.
• Assignment creates references, not copies.
• Names in Python do not have an intrinsic type. Objects have types.
• Python determines the type of the reference automatically based on the data object assigned to it.
• You create a name the first time it appears on the left side of an assignment expression:
x = 3
• A reference is deleted via garbage collection after any names bound to it have passed out of scope.
• If you try to access a name before it’s been properly created (by placing it on the left side of an assignment), you’ll get an error.
In [ ]:
foo_element
• You can also assign to multiple names at the same time.
In [ ]:
x = y = z = 4
print('x =', x, 'y =', y, 'z =', z)
x, y = 4, 2
print('x =', x, 'y =', y, 'z =', z)
In [ ]:
tu = (23, 'abc', 4.56, (2,3), 'def')
# Print first element of tuple
print (tu[0])
# Tuple can be used to assignment also
a, b, c, d, e = tu
print (b)
# Slicing is same just in strings
print (tu[:-2])
tu_2 = ('bar', 'foo')
print (tu + tu_2)
Tuples have many uses, e.g., (x, y) coordinate pairs, employee records from a database, etc. Tuples, like strings, are immutable: it is not possible to assign to the individual items of a tuple.
In [ ]:
li = ["abc", 34, 4.34, 23]
# Appending elements in list
Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on:
In [ ]:
a = ['spam', 'eggs', 100, 1234]
print (a[1:-1])
print (a[:2] + ['bacon', 2*2])
print (3*a[:3] + ['Boe!'])
Operations on List
• The append method adds a single item to the end of the list.
• The extend method adds items from another list (or any sequence) to the end.
• The insert inserts an item at a given index, and move the remaining items to the right.
In [ ]:
a.append('foo')
print (a)
a.extend(li)
print (a)
a.insert(2, 'bar')
print (a)
• The del statement can be used to remove an individual item, or to remove all items identified by a slice.
• The pop method removes an individual item and returns it, while remove searches for an item.
• The removes the first matching item from the list.
In [ ]:
del(a[0])
print (a)
item = a.pop()
print (item)
item = a.pop(1)
print (item)
a.remove('foo')
• Boolean test whether a value is inside a container:
In [ ]:
t = [1, 2, 4, 5]
3 in t
• For strings, tests for substrings
In [ ]:
a = 'abcde'
'a' in a
In [ ]:
for letter in 'Python':
print ('Current Letter :', letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits:
print ('Current fruit :', fruit)
range(start, stop) would return a iterator [start, start+1, ...., stop-1].
In [ ]:
for val in range(0, 10):
print val
In [ ]:
x = -4
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
There can be zero or more elif parts, and the else part is optional. The keyword elif is short for ‘else if’, and is useful to avoid excessive indentation. An if ... elif ... elif ... sequence is a substitute for the switch or case statements found in other languages.
Boolean operators like and, or, not can also be used.
In [ ]:
x = 2
if x == 2 or x == 3:
print 'sucess'
else:
print 'failure'
The keyword def introduces a function definition. It must be followed by the function name and the parenthesized list of formal parameters. The statements that form the body of the function start at the next line, indented by a tab stop.
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
In [ ]:
def foo(num):
print num
foo(2)
The return statement returns with a value from a function. return without an expression argument is used to return from the middle of a procedure (falling off the end also returns from a procedure), in which case the None value is returned.
In [ ]:
def foo_again(num):
return num*2
print foo_again(3)
Default arguments: A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. Following example gives an idea on default arguments, it would print default age if it is not passed:
In [ ]:
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return
# Now you can call printinfo function
printinfo( age=50, name="foo" )
printinfo( name="miki" )